<template>
  <div class='lookOrder'>
    <el-dialog
      title="查看订单"
			:visible.sync="isShow"
      width="95%"
      center
      :before-close="handleClose">
      <el-row :gutter="24">
				<el-col :span="16">
					<div class="grid-content bg-purple">
						<el-form :model="form" ref="ruleForm" label-width="120px">
							<el-row type="flex">
								<el-col :span="12">
									<el-form-item label="专利名称：">{{ form.patent_name }}</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="专利类型：">{{ form.type }}</el-form-item>
								</el-col>
							</el-row>
							<el-row type="flex">
								<el-col :span="12">
									<el-form-item label="订单编号：">{{form.order_number}}</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="订单状态："><font :color='form.status == "已撤案" ? "red" : "green"'>{{ form.status }}</font></el-form-item>
								</el-col>
							</el-row>
							<el-row type="flex">
								<el-col :span="24">
									<el-form-item label="联络人：" >{{ form.liaisons }}</el-form-item>
								</el-col>
							</el-row>
							<el-row type="flex">
								<el-col :span="12">
									<el-form-item label="专利权人：" >{{ form.patent_user }}</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="发明人姓名：" >{{ form.user_name }}</el-form-item>
								</el-col>
							</el-row>


							<el-row>
								<el-col :span="12">
									<el-form-item label="身份证号：" >{{ form.id_card }}</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="联络人：">{{ form.liaisons }}</el-form-item>
								</el-col>
							</el-row>
							<el-row type="flex">
								<el-col :span="12">
									<el-form-item label="联络人邮箱：">{{ form.liaisons_email }}</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="联络人电话：">{{ form.liaisons_tel }}</el-form-item>
								</el-col>
							</el-row>

							<div v-if="form.status == '案件修改中'">
								<el-form-item label="内容审核文件：">
									<div>
										<span class="tips_1" style="color: midnightblue">请直接上传已完成的word文档,单个主体文件,无需分解,仅供内容 审查</span>
										<br />
										<span class="tips_2 unfinish">* 如果多报或者分案或返修等,请分别上传word文件</span>
										<br />
										<template v-if="form.status == '案件修改中'">
											<span class="tips_3 unfinish">* 多报返修文件格式为：订单编号-代理人姓名-案件名称-案件类型-R(数字).docx</span>
											<br />
											<span class="tips_3 unfinish">* 分案返修文件格式为：订单编号-序号(数字)-代理人姓名-案件名称-案件类型-R(数字).docx</span>
										</template>
										<br />
										<span class="tips_2 unfinish">* 免审文件内容要求：
											<el-tooltip placement="top" effect="light">
												<div slot="content" style="line-height: 20px" class="c333">
													实用新型：Word文件内容必须大于<span class="unfinish">12页</span>，<span class="unfinish">4号宋体</span>，<span class="unfinish">1.5倍间距</span>，说明书附图最少<span class="unfinish">2张</span><br />
													发明专利：Word文件内容必须大于<span class="unfinish">18页</span>，<span class="unfinish">4号宋体</span>，<span class="unfinish">1.5倍间距</span>，说明书附图最少<span class="unfinish">4张</span><br />
													免审文件，如果文件内容格式有错误<span class="unfinish">双倍处罚</span>。
												</div>
												<i class="el-icon-question f16 ml5 c333" style="vertical-align: -1px"></i>
											</el-tooltip>
										</span>
									</div>
									<!-- 上传控件 -->
									<div class="upload-wrap">
										<el-upload
											v-if="form.status == '代理人撰写中' || form.status == '案件修改中'"
											ref="upload"
											:auto-upload="true"
											:on-change="handleChange"
											:action="baseUrl + '/api/order/'+ this.form.id +'/upload'"
											:file-list="fileList"
											:http-request="uploadSectionFile"
											:on-remove="handleRemove"
											multiple
											:limit="5">
											<!-- <div slot="tip" class="el-upload__tip">上传文件</div> -->
											<div class="upload-demo-btns">
												<el-button slot="trigger" size="small" type="primary">选择文件</el-button>
											</div>
										</el-upload>
										<div class="free-btn" v-if="form.status == '案件修改中'">
											<el-dropdown trigger="click" placement="bottom" class="free-drop">
												<el-button type="success" size="small">案件上传</el-button>
												<el-dropdown-menu slot="dropdown" class="free-drop-menu">
													<el-dropdown-item class="mb10">
														<el-button size="small" type="primary" class="normal-btn" @click="submitUpload(false)" v-no-more-click:3000>普通案件</el-button>
													</el-dropdown-item>
													<el-dropdown-item>
														<el-button
															:disabled="$store.state.user.trial_free != 1 || !student_finish"
															size="small"
															type="danger"
															class="normal-btn"
															@click="submitUpload(true)"
															v-no-more-click:3000>
															免审案件
														</el-button>
													</el-dropdown-item>
												</el-dropdown-menu>
											</el-dropdown>
										</div>
									</div>
								</el-form-item>

							</div>
              <div v-else>
                <!-- 内审中 不显示上传按钮，显示文件   修改中显示上传文件 并可上传-->
								<el-form-item  label="内容审查文件：" class="flex-line">
									<a v-for="item in form.reviewfileArr" :key="item.id" :href="baseUrl + '/api/download?path='  + item.file +'/'+ item.path"
										:download="item.path" :title="item.path" :class="['el-icon-tickets file_sh', {'free-file': item.path.indexOf('免审') > -1}]"></a>
								</el-form-item>
              </div>

						</el-form>
					</div>
				</el-col>
				<el-col :span="1">
					<br />
				</el-col>

				<!-- 右侧审批意见 + 流程进度 -->
				<el-col :span="7" >
					<div class="grid-content bg-purple r-approval">
						<el-tabs v-model="activeName" @tab-click="handleClick">
							<el-tab-pane label="审批意见" name="first">
								<p v-if="!form.allOpinions">暂无审批意见</p>
								<el-steps direction="vertical" v-else >
									<el-step class="item_tab" v-for="(item, index) in form.allOpinions" :key="item.id">
										<template slot="icon">
											<span> <font class="step-icon_user"> {{ item.review_user[0] }}</font> </span>
										</template>
										<template slot="title">
											<div class="clearfloat">
												<span class="fl msg-user"> <font class="step-title_user">{{ item.review_user }}{{item.from}}</font> {{ item.created_at }}</span>
												<Tooltip content="点我回复" class="fr" v-if="$store.state.user.role_id == 2 && (form.status == '案件修改中' || form.status == '代理人撰写中') && index == 0">
													<i class="el-icon-chat-dot-round leaveWord ml5" @click="agentAnwser(item)"></i>
												</Tooltip>
											</div>
										</template>
										<template slot="description">
											<div class="agent-msg-wrap">
												<div class="agent-msg">
													<span class="title">审核意见：</span>
													<span class="content">
														<span class="clim">
															<span v-if="item.review.indexOf('&&&') == -1">{{item.review}}</span>
															<span v-else>
																{{item.review.split('&&&')[0]}}
																<br />扣款金额：
																<span class="unfinish">{{item.review.split('&&&')[1].split('###')[0]}}元</span>
																<br />扣款原因：
																<span class="unfinish">{{item.review.split('###')[1]}}</span>
															</span>
														</span>
													</span>
												</div>
											</div>
											<div v-if="item.agent_message && item.agent_message.length > 0" class="back-msg">
												<div v-for="(msg, index) in item.agent_message" :key="index" class="agent-msg-wrap">
													<div class="agent-msg-title msg-user">
														<font class="msg-name" style="color: green" v-if="msg.review_user.indexOf('&&&审核员留言') > -1">{{ msg.review_user.split('&&&')[0] }}(审核员)</font>
														<font class="msg-name" v-else-if="msg.review_user.indexOf('&&&学生留言') > -1">{{ msg.review_user.split('&&&')[0] }}</font>
														<font class="msg-name" style="color: green" v-else-if="msg.review_user.indexOf('&&&老师留言') > -1">{{ msg.review_user.split('&&&')[0] }}(导师)</font>
														<font class="msg-name" v-else>{{ msg.review_user }}</font>
														{{ msg.created_at }}
													</div>
													<div class="agent-msg">
														<span class="title">回复内容：</span>
														<span class="content">
															<span class="clim">{{msg.review}}</span>
														</span>
													</div>
												</div>
											</div>
										</template>
									</el-step>
								</el-steps>
							</el-tab-pane>

							<!-- <el-tab-pane label="流程进度" name="second">
								<div class="block">
									<el-timeline v-for="(item,index) in form.statuss" :key="index">
										<el-timeline-item :timestamp="item.pivot.created_at +'  '+item.operation" placement="top">
											<el-card>
												<h4>{{item.name}}</h4>
												<p v-if="item.id == 1">
													发明人：<span class="fontgreen">{{ form.liaisons }}</span>  提交
												</p>
												<p v-if="item.id == 2">
													代理人：<span class="fontgreen">{{ agentNumAddName(form.agent) }}</span> 接单
												</p>
												<p v-if="item.id == 3">
													代理人：<span class="fontgreen">{{ agentNumAddName(form.agent) }}</span> 提交审核文件
												</p>
												<p v-if="item.id == 4">
													审核员：<span class="fontgreen">{{form.auditor_name}}</span> 审核
												</p>
												<p v-if="item.id == 5">
													审核员：<span class="fontgreen">{{form.auditor_name}}</span> 审核
												</p>
												<p v-if="item.id == 7">
													代理人：<span class="fontgreen"> {{ agentNumAddName(form.agent) }}</span>
													提交
												</p>
												<p v-if="item.id == 13">联络人：<span class="fontgreen">{{form.liaisons}}</span> 提交</p>
												<p v-if="index*1<form.statuss.length-1">处理耗时：{{intervalTime(form.statuss[index*1+1].pivot.created_at,form.statuss[index*1].pivot.created_at)}}</p>
											</el-card>
										</el-timeline-item>
									</el-timeline>
								</div>
							</el-tab-pane> -->
						</el-tabs>
					</div>
				</el-col>
			</el-row>

    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data () {
    return {
      isShow: false,
      form: {},
      id: null,
      activeName: "first",
      baseUrl: global.baseurl,
      fileList: [],
      fileListV: [],
      formLen: '',
      activeNum: 1,
    }
  },
  methods: {
    show(data) {
      console.log(data)
      this.id = data.id

      this.getOrderData()
      this.isShow = true
    },
    getOrderData () {
      this.$axios.get(`api/order/${this.id}`).then( res => {
        if (res.data.code == 200) {
          this.splitFile(res.data.data)
          this.getReview(res.data.data)
          this.form = res.data.data
        } else if (res.data.code == 400) {
          this.$message.error(res.data.message)
        }
      })
    },
    // 处理审核文件
    splitFile (data) {
      if (data.review_file == null || data.review_file == "") {} else {
        let fileArr = data.review_file.split("&");
        data.reviewfileArr = [];
        for (const i in fileArr) {
          let itemobj = {
              id: i + 1,
              path: fileArr[i],
              file: ''
          };
          let itemArr = itemobj.path.split("/")
          itemobj.path = itemArr[itemArr.length - 1]
          itemobj.file = itemArr.slice(0, 2).join("/");
          data.reviewfileArr.push(itemobj);
        }
      }
    },
    // 处理审核意见
    getReview (data) {
      //倒转数组
      this.formLen = data.opinions.length;

      if (data.opinions.length == 0 && data.teacher_opinions.length == 0) {
          data.allOpinions = null
      } else {
          data.opinions.reverse();
          data.teacher_opinions.reverse();
          data.opinions.forEach(v => {
              v.from = '（审核员）'
              v.time_code = Date.parse(new Date(v.created_at))
          })
          data.teacher_opinions.forEach(v => {
              v.from = '（导师）'
              v.time_code = Date.parse(new Date(v.created_at))
          })
          data.allOpinions = data.opinions.concat(data.teacher_opinions)
          data.allOpinions.sort((a, b) => a.time_code < b.time_code ? 1 : -1)
          console.log(data.allOpinions)
      }
      this.activeNum = data.opinions.length;
    },
    handleClose () {
      this.form = {}
      this.isShow = false
    },
    // 代理人上传
    submitUpload(type = false) {
      let list = document.getElementsByClassName(
        "el-upload-list__item is-ready"
      );
      if (list.length == 0) {
        this.$message({
          type: "warning",
          message: "请选择需要上传的文件！"
        });
        return;
      }
      // FormData 对象
      var form = new FormData();
      // 免审文件数据处理
      if (type) {
        let free_check = []
        this.fileListV.forEach(v => {
          free_check.push(v.name)
        })
        form.append("free_check", free_check)
      }

      // 文件对象
      for (let i in this.fileListV) {
        form.append(i==0?"file":("file"+(i*1+1)), this.fileListV[i].raw);
      }
      let url = this.baseUrl + "/api/order/" + this.form.id + "/upload"
      // if (this.$store.state.user.is_teacher == 2 && !this.student_finish) {
      //   url =  this.baseUrl + "/api/order/" + this.form.id + "/student_upload"
      // }
      form.append("order", this.form.id);
      if (type) {
        this.$confirm('确认上传免审文件吗', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          center: true,
          type: 'warning'
        }).then(() => {
          this.sumbitPost(url, form)
        }).catch(e => {})
      } else {
        this.sumbitPost(url, form)
      }
    },
    sumbitPost(url, form) {
      axios({
        method: "post",
        url: url,
        data: form,
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: "Bearer " + this.$store.state.token
        }
      }).then(res => {
        if (res.data.status == "success") {
          this.$message({
            type: "success",
            message: "上传成功"
          });
          this.$emit("refresh");
          this.handleClose();
        } else {
          this.$message({
            type: "error",
            message: res.data.message
          });
          this.fileListV=[];
          this.fileList=[];
        }
      }).catch (err => {
        console.log(err)
      })
    },
    //切换流程 和 审批意见
    handleClick(tab, event) {},
    //选择后验证
    handleChange(file, fileList) {
      let tempList = [];//可以上传的文件
      for(let i = 0;i<fileList.length;i ++){
        let canUpload = true;//是否可以上传
        let that = this;
        //验证文件类型
        let fileName = fileList[i].name;
        //文件切成数组 然后去判断格式
        let fileNameArr = fileName.substring(that.form.order_number.length + 1).split("-");
        let arrLen = fileName.split("-").length;
        //1.获取后缀名 必须是文档格式(doc/docx)
        let pos = fileName.lastIndexOf(".");
        let lastName = fileName.substring(pos, fileName.length);
        let orderNum = fileName.substr(0, that.form.order_number.length);
        let typeArr = ['发明专利', '实用新型', '外观设计'] // 专利类型
        if (
          // lastName.toLowerCase() !== ".doc" &&
          lastName.toLowerCase() !== ".docx"
        ) {
          that.$message.error("文件必须为.docx格式");
          canUpload = false;
          //2.拼接订单编号 判断编号是否一致
        }else if (orderNum != that.form.order_number) {
          that.$message.error("文件名中订单编号与订单不符合，请修改后重新上传");
          canUpload = false;
        }else if (that.form.status == "代理人撰写中") {
          if (fileNameArr.length != 3 && fileNameArr.length != 4) {
            that.$message.error('文件名格式不正确')
            canUpload = false;
          } else {
            let type_name = ''
            if (fileNameArr.length == 3) {
              type_name = fileNameArr[2]
            } else if (fileNameArr.length == 4) {
              type_name = fileNameArr[3]
            }
            if (fileNameArr[0] != that.form.agent.name  && fileNameArr[1] != that.form.agent.name) {
              that.$message.error("代理人姓名不一致");
              canUpload = false;
            }
            if (!/^(发明专利|实用新型|外观设计)$/.test(type_name.split(".")[0])) {
              that.$message.error("案件类型必须是【发明专利, 实用新型, 外观设计】中的一种");
              canUpload = false;
            }
            if(fileNameArr.length == 5){
              if (!(/^[0-9]{0,}$/.test(fileNameArr[0]))) {//序号
                that.$message.error("多报格式为订单编号后加'-数字'");
                canUpload = false;
              }
            }
          }
        }else if (that.form.status == "案件修改中") {
          if (fileNameArr.length != 4 && fileNameArr.length != 5) {
            that.$message.error('文件名格式不正确')
            canUpload = false;
          }else{
            if (!(/^R[0-9]{0,}$/.test(fileNameArr[fileNameArr.length - 1].split('.')[0]))) {//R号
              that.$message.error("文件名格式不正确");
              canUpload = false;
            }
            let type_name = ''
            if (fileNameArr.length == 4) {
              type_name = fileNameArr[2]
            } else if (fileNameArr.length == 5) {
              type_name = fileNameArr[3]
            }
            if (fileNameArr[0] != that.form.agent.name  && fileNameArr[1] != that.form.agent.name) {
              that.$message.error("代理人姓名不一致");
              canUpload = false;
            }
            if (!/^(发明专利|实用新型|外观设计)$/.test(type_name.split(".")[0])) {
              that.$message.error("案件类型必须是【发明专利, 实用新型, 外观设计】中的一种");
              canUpload = false;
            }
            if(fileNameArr.length == 5){
              if (!(/^[0-9]{0,}$/.test(fileNameArr[0]))) {//序号
                that.$message.error("多报格式为订单编号后加'-数字'");
                canUpload = false;
              }
            }
          }
        }
        if(canUpload){
          tempList.push(fileList[i]);
        }
      }
      this.fileListV.splice(0,this.fileListV.length,...tempList);
      fileList.splice(0,fileList.length,...tempList);
      return ;
    },
    //上传
    uploadSectionFile(params) {
    },
    handleRemove(file, fileList) {
      this.fileListV = fileList;
    },
  },
  watch: {
    form: {
      handler: function (val) {
        if (val.update_records) {
          if (val.update_records.length) {
              for (let i = 0; i < val.update_records.length; i++) {
                if( val.update_records[i].review instanceof Object ) {
                  this.isUpdate = false
                  break
                }  else {
                  this.isUpdate = true
                }
              }
          } else {
            this.isUpdate = true
          }
        }
        if (this.$store.state.user.is_teacher != 2) {
          this.student_finish = true
        } else {
          this.student_finish = false
          if (val.statuss) {
            if (val.statuss.findIndex(v => v.id == 5) > -1) {
              let statuss = val.statuss.slice(0, val.statuss.findIndex(v => v.id == 5))
              if (statuss.findIndex(v => v.id == 16) > -1) {
                if (statuss.findIndex(v => v.id == 17) > -1) {
                  this.student_finish = true
                  return this.student_upload = false
                }
                if (statuss.findIndex(v => v.id == 17) == -1 && statuss.findIndex(v => v.id == 18) == -1 && statuss.findIndex(v => v.id == 16) > -1) {
                  return this.student_upload = true
                }
                if (statuss.findIndex(v => v.id == 18) > statuss.findIndex(v => v.id == 16)) {
                  return this.student_upload = true
                }
              }
              if (val.statuss.findIndex(v => v.id == 5) < val.statuss.findIndex(v => v.id == 3)) {
                return this.student_upload = false
              }
            } else {
              if (val.statuss.findIndex(v => v.id == 17) > -1) {
                this.student_finish = true
                return this.student_upload = false
              }
              if (val.statuss.findIndex(v => v.id == 17) == -1 && val.statuss.findIndex(v => v.id == 18) == -1 && val.statuss.findIndex(v => v.id == 16) > -1) {
                return this.student_upload = true
              }
              if (val.statuss.findIndex(v => v.id == 18) > val.statuss.findIndex(v => v.id == 16)) {
                return this.student_upload = true
              }
            }
          }
        }
      },
      deep: true,
      immediate: true
    },
  }
}
</script>

<style lang='less' type='text/css'>
  .lookOrder {
    .flex-line {
      .el-form-item__content {
        display: flex;
        height: 40px;
        align-items: center;
      }
    }
    .upload-wrap {
		display: flex;
		position: relative;
		.upload-demo {
			width: 400px;
			.el-upload-list__item-name {
				margin-right: 0px;
			}
		}
		.free-btn {
			position: absolute;
			line-height: 40px;
			left: 65px;
			margin-left: 15px;
			// .el-button {
			// 	height: 26px;
			// }

		}
		.free-wrap {
			margin-left: 10px;
			.checkbox-wrap {
				.el-checkbox-group {
					.el-checkbox {
						line-height: 20px;
						.el-checkbox__inner {
							border-color: #409EFF;
						}
						.el-checkbox__label {
							color: #409EFF;
						}
					}
				}
			}
			.checkbox-line {
				margin-top: 5px;
				height: 25px;
				display: flex;
				align-items: center;
				&:first-child {
					margin-top: 10px;
				}
			}
		}
	}
    .el-form-item {
			height: 100%;
			border: 1px solid #ccc;
			margin-right: -1px;
			margin-bottom: -1px;
		}

		.el-col {
			.el-col-12 {
				.el-form-item {
					border-bottom-width: 0;
				}
			}
    }


    .el-steps {
			.el-step {
				.el-step__main {
					padding-left: 20px;
					.el-step__title {
						color: #909399;
						font-size: 14px;
					}
				}
			}
			.el-step__icon-inner{
				display: none !important; //不要序号
			}
			.step-icon_user {
				color: #FFF;
				// margin-left: 10px ;
				font-size: 14px;
			}
			.step-title_user {
				color: green;
				margin-right: 10px ;
				font-size: 15px;
			}
			.el-step__line {
				display: none;
			}
			.el-step__icon {
				background: #409EFF;
				border: 0px;
				width: 28px;
				height: 28px;
			}
			.el-step__description {
				color: rgb(58, 58, 58);
			}
    }
    .file_sh {
			font-size: 32px;
			margin-right: 40px;
		}
  }
</style>
